package uno;

import static org.junit.Assert.*;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;

import java.io.*;
import java.net.URL;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.Properties;
import java.security.cert.Certificate;

import org.junit.Test;
import org.springframework.core.io.ClassPathResource;

public class Complete {

	String url = "https://sede.dgt.gob.es/es/";
	String cacert = "ACRAIZFNMTRCM.crt";

	// String url = "http://org-nekperu15739-me.appspot.com/";

	protected File getKeyStoreFile() {
		String javaHome = System.getProperty("java.home");
		String filename = javaHome
				+ "/lib/security/".replace('/', File.separatorChar);
		File path = new File(filename);
		File file = new File(path, "jssecacerts");
		if (!file.exists()) {
			file = new File(path, "cacerts");
			if (!file.exists()) {
				file = null;
			}
		}

		return file;
	}

	protected KeyStore getKeyStore(File file) throws KeyStoreException,
			NoSuchAlgorithmException, CertificateException, IOException {
		System.out.println("Loading KeyStore " + file + "...");
		InputStream inputStream = new FileInputStream(file);
		KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
		keyStore.load(inputStream, null);
		inputStream.close();
		System.out.println("#certificados=" + keyStore.size());
		return keyStore;
	}

	protected Certificate getCertificate() throws CertificateException, FileNotFoundException, IOException {
		CertificateFactory cf = CertificateFactory.getInstance("X.509");
		ClassPathResource resource = new ClassPathResource(cacert);
		FileInputStream in1 = new FileInputStream(resource.getFile());
		Certificate certificate = cf.generateCertificate(in1);
		in1.close();
		return certificate;
	}

	@SuppressWarnings("unused")
	@Test
	public void test() throws KeyStoreException, NoSuchAlgorithmException,
			CertificateException, IOException, UnrecoverableKeyException {

		File keyStoreFile = getKeyStoreFile();
		System.out.println(keyStoreFile);
		KeyStore keyStore = getKeyStore(keyStoreFile);
		System.out.println("certificados N="+keyStore.size());
		Certificate certificate = getCertificate();
		
	    char[] lfstorepass = "changeit".toCharArray();
		char[] lfkeypass = "changeit".toCharArray();
//	    PrivateKey prk = (PrivateKey) keyStore.getKey("lf", lfkeypass);

		String alias = "dgt";
		
		//		keyStore.setKeyEntry("dgt", prk, lfstorepass, certificate);
//		keyStore.setKeyEntry(alias, key, chain);
		keyStore.setCertificateEntry(alias, certificate);
		System.out.println("certificados N="+keyStore.size());
	    FileOutputStream fileOutputStream = new FileOutputStream("jssecacertsOut.jks");
	    keyStore.store(fileOutputStream, "changeit".toCharArray());
	    fileOutputStream.close();
		

		/*
		 * System.setProperty("javax.net.ssl.trustStore",
		 * "/Users/charly/workspace/google/org/nekperu15739/workspace/CertificadosDigitales/src/test/resources/jssecacerts.jks"
		 * ); System.setProperty("javax.net.ssl.trustStorePassword",
		 * "changeit"); // URL resource =
		 * Complete.class.getResource("resources:jssecacerts.jks");
		 * 
		 * 
		 * // $JAVA_HOME/lib/security/jssecacerts //
		 * $JAVA_HOME/lib/security/cacerts
		 * 
		 * String filename = "jssecacerts.jks"; ClassPathResource
		 * classPathResource = new ClassPathResource(filename); File f = new
		 * File(filename); boolean exists = f.exists(); boolean exists2 =
		 * classPathResource.exists();
		 * 
		 * FileInputStream is = new
		 * FileInputStream(classPathResource.getFile()); KeyStore keystore =
		 * KeyStore.getInstance(KeyStore.getDefaultType()); String password =
		 * "password"; keystore.load(is, null);
		 * 
		 * System.out.println("certificados N="+keystore.size());
		 * 
		 * 
		 * String property2 = System.getProperty("javax.net.ssl.keyStore");
		 */
		// javax.net.ssl.trustStore
		// String property = System.getProperty("javax.net.ssl.trustStore");

		// Properties properties = System.getProperties();

		// System.out.println(properties.toString());

		// Create an instance of HttpClient.
		HttpClient client = new HttpClient();

		// Create a method instance.
		GetMethod method = new GetMethod(url);

		// Provide custom retry handler is necessary
		method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler(3, false));

		try {
			// Execute the method.
			int statusCode = client.executeMethod(method);

			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed: " + method.getStatusLine());
			}

			// Read the response body.
			byte[] responseBody = method.getResponseBody();

			// Deal with the response.
			// Use caution: ensure correct character encoding and is not binary
			// data
			System.out.println(new String(responseBody));

		} catch (HttpException e) {
			System.err.println("Fatal protocol violation: " + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("Fatal transport error: " + e.getMessage());
			e.printStackTrace();
		} finally {
			// Release the connection.
			method.releaseConnection();
		}
	}

}
